//
//  ZHTabBarView.swift
//  ZHWeibo
//
//  Created by user on 15/12/5.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit
class ZHTabBarView: UITabBar {
    
    //定义闭包闭包变量----使得控制器能够根据点击的按钮做相应的动作
    var addBtnclosure: (()->())?
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //self.backgroundColor = UIColor.redColor()
        self.tintColor = UIColor.orangeColor()
        self.addSubview(self.addBtn)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //懒加载设置addBtn
    /// 为什么懒加载不能使用let
    private lazy var addBtn:UIButton = {
        let Btn:UIButton = UIButton()
        //添加监听事件
        Btn.addTarget(self, action: "clickAddBtn", forControlEvents: UIControlEvents.TouchUpInside)
        //添加背景图片
        // 设置按钮的背景图片
        Btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        Btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        // 设置不同状态的图片
        Btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        Btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        //设置frame
        Btn.sizeToFit()
        return Btn
    }()
    @objc private func clickAddBtn (){
        //执行闭包
        self.addBtnclosure?()
    }
    
    //添加tabItem的frame
    override func layoutSubviews() {
        super.layoutSubviews()
        let ItemWidth:CGFloat = UIScreen.mainScreen().bounds.width * 0.2
        //设置中间Btn的位置-----不能使用tabBar的center
        self.addBtn.center = CGPoint(x: frame.width * 0.5, y: frame.height * 0.5)
        //设置其他Item的frame
        
        var index:Int = 0
        for Item in self.subviews {
            if Item.isKindOfClass(NSClassFromString("UITabBarButton")!){
                if index == 2 {
                    index++
                }
                let ItemX:CGFloat = CGFloat(index) * ItemWidth
                Item.frame = CGRectMake(ItemX, 0, ItemWidth, bounds.height)
                index++
            }
        }
        
    }
}
